<?php

namespace admin\controllers;

use Yii;
use admin\models\Order;
use admin\models\User;
use common\helpers\Hui;
use common\helpers\Html;

class OrderController extends \admin\components\Controller
{
    /**
     * @authname 订单列表
     */
    public function actionList()
    {
        $query = (new Order)->listQuery()->joinWith(['product.dataAll', 'user.parent', 'user.adminUser'])->orderBy('order.id DESC');
        $countQuery = (new Order)->listQuery()->joinWith(['product.dataAll', 'user.parent', 'user.adminUser'])->andWhere(['user.type' => User::TYPE_USER]);

        // 今日盈亏统计，交易额、手数
        $profit = $countQuery->andWhere(['order.order_state' => Order::ORDER_THROW, 'user.type' => User::TYPE_USER])->select('SUM(order.profit) profit')->one()->profit ?: 0 ;
        $amount = $countQuery->select('SUM(order.deposit) deposit')->one()->deposit ?: 0;
        $hand = $countQuery->select('SUM(order.hand) hand')->one()->hand ?: 0;
        $fee = $countQuery->select('SUM(order.fee) fee')->one()->fee ? : 0;

        $html = $query->getTable([
            'user.id',
            'user.nickname',
            // ['header' => '推荐人', 'value' => function ($row) {
            //     return $row->user->getParentLink('user.id');
            // }],
            'user.pid' => ['header' => '推荐人ID'],
            'adminUser.username' => ['header' => '代理商账号'],
            'product.name',
            'created_at',
            'user.type',
            'updated_at' => function ($row) {
                return $row['order_state'] == Order::ORDER_POSITION ? '' : $row['sell_time'];
            },
            'rise_fall' => ['header' => '涨跌', 'value' => function ($row) {
                return $row['rise_fall'] == Order::RISE ? Html::redSpan('买涨') : Html::greenSpan('买跌');
            }],
            ['header' => '下单类型', 'value' => function($row) {
                if (empty($row->stop_profit_point) || $row->stop_profit_point == 0) {
                    return strtotime($row['sell_time']) - strtotime($row['created_at']).'秒';
                }
                return floatval($row->stop_profit_point).'秒';
            }],
            'price',
            'fee',
            'sell_price' => function ($row) {
                if ($row['order_state'] == Order::ORDER_POSITION) {
                    return '';
                } else {
                    if ($row['price'] < $row['sell_price']) {
                        return Html::redSpan($row['sell_price']);
                    } else {
                        return Html::greenSpan($row['sell_price']);
                    }
                }
            },
            'deposit',
            'profit' => function ($row) {
                return $row['profit'] >= 0 ? Html::redSpan($row['profit']) : Html::greenSpan($row['profit']);
            },
            // 'user.account',
            'order_state',
            ['type' => [], 'value' => function ($row) {
                if ($row['order_state'] == Order::ORDER_POSITION) {
                    return Hui::primaryBtn('平仓', ['sellOrder', 'id' => $row['id']], ['class' => 'sellOrder']);
                }
            }]
        ], [
            'ajaxReturn' => [
                'countProfit' => '盈亏统计：' . ($profit >= 0 ? Html::redSpan($profit) : Html::greenSpan($profit)) . '，',
                'countAmount' => $amount,
                'countHand' => $hand,
                'countFee' => $fee
            ],
            'searchColumns' => [
                'user.id',
                'user.pid'=> ['header' => '推荐人ID'],
                'adminUser.username' => ['header' => '代理商账号'],
                'product_name' => ['type' => 'select', 'header' => '选择产品'],
                'user.type' => ['type' => 'select'],
                // 'user.nickname',
                // 'start_time' => ['header' => '下单时间', 'type' => 'date'],
                'time' => ['header' => '下单时间', 'type' => 'dateRange'],
                'parent.mobile' => ['header' => '推荐人手机号'],
                'is_profit' => ['type' => 'select', 'header' => '是否盈亏'],
                'order_state' => 'select'
            ]
        ]);


        return $this->render('list', compact('html', 'profit', 'amount', 'hand', 'fee'));
    }

    /**
     * @authname 手动平仓
     */
    public function actionSellOrder()
    {
        $id = get('id');
        $price = post('price');
        if ($price < 0 || !is_numeric($price)) {
            return error('价格数据非法！');
        }
        if (Order::sellOrder($id, $price)) {
            return success('成功平仓');
        } else {
            return error('此单已平');
        }
    }

    public function actionCurrentList()
    {
        $map = ['order.order_state' => Order::ORDER_POSITION];
        $query = (new Order)->listQuery()->joinWith(['product.dataAll', 'user.parent', 'user.admin'])->manager()->filterWhere($map)->orderBy('order.id DESC');

        $html = $query->getTable([
            'user.id',
            'user.nickname',
            ['header' => '推荐人(ID)', 'value' => function ($row) {
                return $row->user->getParentLink('user.id');
            }],
            'admin.username' => ['header' => '代理商账户'],
            'product.name',
            'created_at',
            'updated_at' => function ($row) {
                return $row['order_state'] == Order::ORDER_POSITION ? '' : $row['updated_at'];
            },
            'rise_fall' => ['header' => '涨跌', 'value' => function ($row) {
                return $row['rise_fall'] == Order::RISE ? Html::redSpan('买涨') : Html::greenSpan('买跌');
            }],
            'price',
            'fee',
            'sell_price' => function ($row) {
                if ($row['order_state'] == Order::ORDER_POSITION) {
                    return '';
                } else {
                    if ($row['price'] < $row['sell_price']) {
                        return Html::redSpan($row['sell_price']);
                    } else {
                        return Html::greenSpan($row['sell_price']);
                    }
                }
            },
            'hand',
            'deposit',
            'profit' => function ($row) {
                return $row['profit'] >= 0 ? Html::redSpan($row['profit']) : Html::greenSpan($row['profit']);
            },
            'user.account',
            'order_state'
        ]);

        return $html;
    }
}
